
const TreeNode = {
    props: ['node'],
    template: `
        <div class="tree-node">
            <span class="tree-toggle" @click.stop="toggleExpand" v-if="node.children">
                {{ node.expanded ? '−' : '+' }}
            </span>
            <span @click.stop="selectNode">{{ node.label }} </span>
            <div v-if="node.expanded && node.children" class="children">
                <tree-node 
                    v-for="child in node.children" 
                    :key="child.id" 
                    :node="child"
                    @select="onChildSelect">
                </tree-node>
            </div>
        </div>
    `,
    methods: {
        toggleExpand() {
            this.node.expanded = !this.node.expanded;
            console.log('===this.node.expanded:',this.node.expanded);
            console.log('===this.node:',this.node);
        },
        selectNode() {
            console.log('====selectNode:',this.node);

            this.$emit('select', this.node);
        },
        onChildSelect(node) {
            console.log('===onChildSelect:',node);
            this.$emit('select', node);
        }
    }
};

/**
 * 树形节点选择组件
 * 可在任意界面通过<tree-node-select>标签使用
 */

// 定义树节点选择组件
const TreeNodeSelect = {
    props: ['node'],
    template: `
        <div class="tree-node">
            <span class="tree-toggle" @click.stop="toggleExpand" v-if="node.children">
                {{ node.expanded ? '−' : '+' }}
            </span>
            <!-- 向右移一个空格 -->

            <input
                type="checkbox"
                :indeterminate.prop="node.indeterminate"
                v-model="node.checked"
                @click.stop="toggleCheck">
            <span @click.stop="selectNode">{{ node.label }}</span>
            <div v-if="node.expanded && node.children" class="children">
                <tree-node-select
                    v-for="child in node.children"
                    :key="child.id"
                    :node="child"
                    @update:checked="updateParentState">
                </tree-node-select>
            </div>
        </div>
    `,
    watch: {
        // 监听节点数据变化
        'node.checked': {
            handler(newVal) {
                // 向上更新父节点状态
                this.$emit('update:checked', newVal);
            }
        },
        // 深度监听节点及其子节点数据变化
        node: {
            handler() {
                // 重新计算节点状态
                this.recalculateNodeState();
            },
            deep: true
        }
    },
    methods: {
        toggleExpand() {
            this.node.expanded = !this.node.expanded;
        },
        toggleCheck() {
            // 改变当前节点的选中状态
            this.node.checked = !this.node.checked;
            this.node.indeterminate = false;

            // 如果是父节点（有子节点），则同步更新所有子节点状态
            if (this.node.children && this.node.children.length > 0) {
                this.updateChildrenState(this.node, this.node.checked);
            }

            // 向上更新父节点状态
            this.$emit('update:checked', this.node.checked);
        },
        // 用于批量更新子节点状态的方法
        updateChildrenState(node, checked) {
            if (node.children) {
                node.children.forEach(child => {
                    child.checked = checked;
                    child.indeterminate = false;
                    this.updateChildrenState(child, checked);
                });
            }
        },
        // 全选所有子节点
        selectAllChildren() {
            this.updateChildrenState(this.node, true);
        },
        // 取消选择所有子节点
        unselectAllChildren() {
            this.updateChildrenState(this.node, false);
        },
        selectNode() {
            this.toggleCheck();
        },
        updateParentState() {
            if (this.node.parent) {
                const parent = this.node.parent;
                const checkedCount = parent.children.filter(c => c.checked).length;
                const indeterminateCount = parent.children.filter(c => c.indeterminate).length;

                if (checkedCount === 0 && indeterminateCount === 0) {
                    parent.checked = false;
                    parent.indeterminate = false;
                } else if (checkedCount === parent.children.length) {
                    parent.checked = true;
                    parent.indeterminate = false;
                } else {
                    parent.checked = false;
                    parent.indeterminate = true;
                }

                // 递归更新所有祖先节点
                if (parent.parent) {
                    this.$emit('update:checked', parent.checked);
                }
            }
        },
        // 重新计算节点状态
        recalculateNodeState() {
            // 如果有子节点，根据子节点状态更新当前节点
            if (this.node.children && this.node.children.length > 0) {
                const checkedCount = this.node.children.filter(c => c.checked).length;
                const indeterminateCount = this.node.children.filter(c => c.indeterminate).length;

                if (checkedCount === 0 && indeterminateCount === 0) {
                    this.node.checked = false;
                    this.node.indeterminate = false;
                } else if (checkedCount === this.node.children.length) {
                    this.node.checked = true;
                    this.node.indeterminate = false;
                } else {
                    this.node.checked = false;
                    this.node.indeterminate = true;
                }

                // 向上更新父节点状态
                this.$emit('update:checked', this.node.checked);
            }
        }
    },
    mounted() {
        // 组件挂载时，初始计算一次节点状态
        this.recalculateNodeState();
    }
};

// 为了在全局注册组件，提供一个注册函数
function registerTreeNodeSelect(app) {
    app.component('tree-node-select', TreeNodeSelect);
}

// 导出组件和注册函数，支持不同的引入方式
if (typeof exports !== 'undefined') {
    // CommonJS模块导出
    exports.TreeNodeSelect = TreeNodeSelect;
    exports.registerTreeNodeSelect = registerTreeNodeSelect;
} else if (typeof window !== 'undefined') {
    // 浏览器全局变量
    window.TreeNodeSelect = TreeNodeSelect;
    window.registerTreeNodeSelect = registerTreeNodeSelect;
}



// 树形数据处理工具函数
const TreeUtils = {
    /**
     * 设置父节点引用，并确保expanded状态保留
     * @param {Array} nodes - 树节点数组
     * @param {Object} parent - 父节点
     * @returns {Array} - 处理后的树节点数组
     */
    setParentReferences(nodes, parent = null) {
      return nodes.map(node => {
        // 创建节点的副本，避免直接修改原始对象
        const newNode = {...node};
        // 设置父节点引用
        newNode.parent = parent;
        // 确保expanded有值
        newNode.expanded = newNode.expanded || false;
        
        // 处理子节点
        if (newNode.children && newNode.children.length) {
          newNode.children = this.setParentReferences(newNode.children, newNode);
        }
        return newNode;
      });
    },
  
    /**
     * 计算父节点的选中状态
     * @param {Array} nodes - 树节点数组
     * @returns {Array} - 处理后的树节点数组
     */
    calculateParentState(nodes) {
      // 首先递归处理所有子节点
      if (nodes && nodes.length) {
        nodes.forEach(node => {
          if (node.children && node.children.length) {
            this.calculateParentState(node.children);
          }
        });
        
        // 然后处理当前层级的父节点
        nodes.forEach(node => {
          if (node.parent && node.parent.children) {
            const siblings = node.parent.children;
            const checkedCount = siblings.filter(c => c.checked).length;
            const indeterminateCount = siblings.filter(c => c.indeterminate).length;
            
            if (checkedCount === 0 && indeterminateCount === 0) {
              // 没有选中或半选中的子节点
              node.parent.checked = false;
              node.parent.indeterminate = false;
            } else if (checkedCount === siblings.length) {
              // 所有子节点都选中
              node.parent.checked = true;
              node.parent.indeterminate = false;
            } else {
              // 部分子节点选中或半选中
              node.parent.checked = false;
              node.parent.indeterminate = true;
            }
          }
        });
      }
      
      return nodes;
    },
  
    /**
     * 移除parent引用，防止循环引用导致JSON序列化错误
     * @param {Array} nodes - 树节点数组
     * @returns {Array} - 处理后的树节点数组
     */
    removeParentReferences(nodes) {
      return nodes.map(node => {
        // 创建一个没有parent属性的节点副本
        const { parent, ...newNode } = {...node};
        
        // 处理子节点
        if (newNode.children && newNode.children.length) {
          newNode.children = this.removeParentReferences(newNode.children);
        }
        return newNode;
      });
    },
  
    /**
     * 处理树数据为可用状态（添加父引用并计算选中状态）
     * @param {Array} treeData - 原始树数据
     * @returns {Array} - 处理后的树数据
     */
    processTreeData(treeData) {
      let processedData = this.setParentReferences(treeData);
      processedData = this.calculateParentState(processedData);
      return processedData;
    }
  };
  